import { BaseTable } from '../db/table'
import { Result } from './index'
import moment from 'moment'

export interface IArticle {
  content?: string
  keys?: string
  create_time?: number | string | Date
  update_time?: number | string | Date
  version?: number
}

/**
 * 文件内容对象
 */
export class ArticleModel implements IArticle {
  public content?: string
  public keys?: string
  public create_time?: number | string | Date
  public update_time?: number | string | Date
  public version?: number

  constructor(opt: IArticle) {
    this.content = opt.content
    this.keys = opt.keys
    this.update_time = moment().format()
    this.create_time = moment().format()

    Object.assign(this, opt)
  }
}

export class ArticleService extends BaseTable {
  public declare db: IDBDatabase
  public table: string

  constructor(db: IDBDatabase, table: string) {
    super()
    this.db = db
    this.table = table
  }

  /** 添加文章 */
  async addArticle(data: IArticle) {
    let article = new ArticleModel(data)
    let res: Result = new Result()
    try {
      res.data = await this.add(this.table, article)
      res.code = 1
    } catch (err) {
      res.code = 0
      res.msg = err.message
    }

    return res
  }

  /** id 查找文章 */
  async findById(id: number) {
    let res: Result = new Result()
    try {
      res.data = await this.getById(this.table, id)
      res.code = 1
    } catch (err) {
      res.code = 0
      res.msg = err.message
    }

    return res
  }

  /** 更新文章 */
  async updata(data: IArticle): Promise<Result<ArticleModel>> {
    let article = new ArticleModel({ ...data })
    article.update_time = moment().format()

    let res: Result<ArticleModel> = new Result<ArticleModel>()
    try {
      res.data = await this.put(this.table, article)
      res.code = 1
    } catch (err) {
      res.code = 0
      res.msg = err.message
    }

    return res
  }

  /** 删除 */
  async delete(id: number) {
    let res: Result = new Result()
    try {
      res.data = await this.del(this.table, id)
      res.code = 1
    } catch (err) {
      res.code = 0
      res.msg = err.message
    }

    return res
  }
}
